import React, { useState } from 'react';
import { Button, message, Modal, Spin, Tooltip } from 'antd'; // 导入 Tooltip 组件
import axios from '@/components/service/request.js';

const FetchImages = ({ filePath }) => {
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [loadingText, setLoadingText] = useState('');

  const fetchImages = async () => {
    if (!filePath) {
      return message.error('请先上传文件');
    }

    setLoading(true);
    setLoadingText('正在获取图片，请稍候...');

    try {
      const response = await axios.get('/model/get', { params: { fileName: filePath } });
      if (response.code === 200) {
        const images = response.data?.map((base64String) => `data:image/png;base64,${base64String}`) || [];
        setImages(images);
        message.success('图片获取成功');
      } else if (response.code === 404) {
        message.error('文件未找到，请检查文件路径');
      } else {
        message.error(`获取图片失败，状态码: ${response.code}`);
      }
    } catch (error) {
      console.error('获取图片失败:', error);
      if (error.response) {
        message.error(`请求失败，状态码: ${error.response.code}`);
      } else {
        message.error('获取图片失败，请检查网络连接');
      }
      setImages([]);
    } finally {
      setLoading(false);
      setLoadingText('');
    }
  };

  const handleImageClick = (base64Image) => {
    const byteString = atob(base64Image.split(',')[1]);
    const mimeType = base64Image.split(',')[0].match(/:(.*?);/)[1];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([ab], { type: mimeType });
    const blobUrl = URL.createObjectURL(blob);

    window.open(blobUrl, '_blank');
  };

  return (
    <>
      <Button type="primary" onClick={fetchImages} style={{ marginTop: 16 }} disabled={loading}>
        获取图片
      </Button>
      <Modal open={loading} footer={null} closable={false} maskClosable={false} centered>
        <Spin tip={loadingText} size="large" />
        <p>{loadingText}</p>
      </Modal>
      <div className="image-grid">
        {images.map((src, index) => (
          <Tooltip key={index} title="点击查看详情">
            <img
              src={src}
              alt={`模型图片 ${index}`}
              onClick={() => handleImageClick(src)}
              style={{ cursor: 'pointer' }}
            />
          </Tooltip>
        ))}
      </div>
    </>
  );
};

export default FetchImages;
